package com.dokimall.dokimallseckill.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dokimall.common.to.mq.SeckillOrderTo;
import com.dokimall.common.utils.R;
import com.dokimall.common.vo.MemberVo;
import com.dokimall.dokimallseckill.feign.CouponFeignService;
import com.dokimall.dokimallseckill.feign.ProductFeignService;
import com.dokimall.dokimallseckill.interceptor.SeckillInterceptor;
import com.dokimall.dokimallseckill.service.SeckillService;
import com.dokimall.dokimallseckill.vo.SeckillSessionVo;
import com.dokimall.dokimallseckill.vo.SeckillSkuRedisTo;
import com.dokimall.dokimallseckill.vo.SkuInfoVo;
import org.apache.logging.log4j.util.Strings;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public final String SESSION_CACHE_PREFIX = "seckill:session:";

    public final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    public final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void upSeckillLast3Day() {
        // 扫描最近三天将要参与秒杀的商品
        R r = couponFeignService.get3daysSeckill();
        if(r.getCode()==0){
            List<SeckillSessionVo> sessionData = r.getData(new TypeReference<List<SeckillSessionVo>>() {
            });
            if(sessionData!=null && sessionData.size()>0){
                // 缓存到redis
                // 1、缓存活动信息
                saveSessionInfo(sessionData);
                // 2、缓存活动的关联商品信息
                saveSessionSkuInfo(sessionData);
            }
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSku() {
        // 去redis查找有没有符合当前时段的秒杀商品
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        long time = new Date().getTime(); // 当前时间
        if(keys!=null && keys.size()>0){
            for (String key : keys) {
                String replace = key.replace(SESSION_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long startTime = Long.parseLong(s[0]);
                Long endTime = Long.parseLong(s[1]);
                if(time>=startTime && time<=endTime){
                    // 符合当前秒杀时间的商品
                    // 查出当前场次的全部商品信息，value值
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> operations = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = operations.multiGet(range);
                    if(list!=null && list.size()>0){
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            return skuRedisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        // 查出缓存中的秒杀商品信息
        BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = boundHashOps.keys();
        if(keys!=null && keys.size()>0){
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                boolean matches = Pattern.matches(regx, key);
                if(matches){
                    String s = boundHashOps.get(key);
                    SeckillSkuRedisTo seckillSkuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
                    return seckillSkuRedisTo;
                }
            }
        }

        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        // 获取当前秒杀商品的详细信息；
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        // 校验合法性
        if(StringUtils.isEmpty(s)){
            return null;
        }else {
            SeckillSkuRedisTo skuRedisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
            // 校验时间合法性
            Long startTime = skuRedisTo.getStartTime();
            Long endTime = skuRedisTo.getEndTime();
            Long now = new Date().getTime();
            if (now>=startTime && now<=endTime){
                // 校验随机码以及商品id是否合法
                String token = skuRedisTo.getToken();
                String skuId = skuRedisTo.getPromotionSessionId()+"_"+skuRedisTo.getSkuId();
                if (token.equals(key) && skuId.equals(killId)){
                    // 检验购买的商品数量是否合法
                    int limit = skuRedisTo.getSeckillLimit().intValue(); // 每人最大购买量
                    if(num<=limit){
                        // 验证该用户是否已经购买过商品，幂等性；如果秒杀成功就去redis占位  userId_SessionId_skuId
                        MemberVo memberVo = SeckillInterceptor.threadLocal.get();
                        // 设置自动过期，秒杀活动结束就清掉
                        Long ttl = endTime - now;
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(memberVo.getId() + "_" + skuId, num.toString(),ttl, TimeUnit.MILLISECONDS);
                        if(aBoolean){
                            // 占位成功，扣减信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + key);

                                // Acquire 如果获取不到会阻塞等待信号量释放，tryAcquire 会在指定时间尝试获取，获取不了直接放弃
                                boolean b = semaphore.tryAcquire(num);
                                // 获取信号量成功，生成订单号，快速下单给MQ发送消息
                                if(b){
                                    String orderSn = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(orderSn);
                                    orderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
                                    orderTo.setNum(num);
                                    orderTo.setSkuId(skuRedisTo.getSkuId());
                                    orderTo.setPromotionSessionId(skuRedisTo.getPromotionSessionId());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    return orderSn;
                                }
                            }
                        }
                    }
                }
                return null;
            }
        }

    private void saveSessionSkuInfo(List<SeckillSessionVo> sessionData) {
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        sessionData.stream().forEach(session->{
            session.getRelationEntities().stream().forEach(seckillInfo -> {
                SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();
                // 秒杀信息
                BeanUtils.copyProperties(seckillInfo,skuRedisTo);
                // 生成随机码
                String token = UUID.randomUUID().toString().replace("-","");
                skuRedisTo.setToken(token);

                if(!boundHashOps.hasKey(seckillInfo.getPromotionSessionId()+"_"+seckillInfo.getSkuId().toString())){
                    // 商品的详细信息
                    R info = productFeignService.info(seckillInfo.getSkuId());
                    if(info.getCode()==0){
                        SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfoVo(skuInfo);
                    }

                    // 秒杀开始、结束时间
                    skuRedisTo.setStartTime(session.getStartTime().getTime());
                    skuRedisTo.setEndTime(session.getEndTime().getTime());


                    // 使用库存作为分布式的信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(seckillInfo.getSeckillCount().intValue());

                    // 保存到redis中
                    String string = JSON.toJSONString(skuRedisTo);
                    boundHashOps.put(seckillInfo.getPromotionSessionId()+"_"+seckillInfo.getSkuId().toString(),string);
                }
            });
        });
    }

    private void saveSessionInfo(List<SeckillSessionVo> sessionData) {
        if(sessionData!=null){
            sessionData.stream().forEach(data->{
                long startTime = data.getCreateTime().getTime();
                long endTime = data.getEndTime().getTime();
                String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean aBoolean = redisTemplate.hasKey(key);
                if(!aBoolean){
                    List<String> collect = data.getRelationEntities().stream().map(item -> item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                    // 缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key,collect);
                }
            });
        }
    }
}
